package com.pxml2pdf.utility;

import java.net.URL;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.itextpdf.text.FontFactory;

public class FontUtility {
	private static final String NODE_fontFamily = "fontFamily";
	private static final String NODE_normal = "normal";
	private static final String NODE_bold = "bold";
	private static final String NODE_italic = "italic";
	private static final String NODE_boldItalic = "boldItalic";
	// private static final String NODE_pdfEncoding = "pdfEncoding";
	// private static final String NODE_pdfEmbedded = "pdfEmbedded";
	// private static final String NODE_exportFonts = "exportFonts";
	// private static final String NODE_export = "export";
	// private static final String NODE_locales = "locales";
	// private static final String NODE_locale = "locale";
	// private static final String ATTRIBUTE_key = "key";
	private static final String ATTRIBUTE_name = "name";

	public static void registerFont() {
		registerFont("fonts/fontsfamily1376643627247.xml");
		registerFont("fonts/fontsfamily1379408560992.xml");
	}

	private static void registerFont(String fonts) {
		List<URL> list = X2pUtility.getResources(fonts);
		for (URL url : list) {
			// System.out.println(url.getPath());
			SAXReader reader = new SAXReader();
			try {
				Document document = reader.read(url);
				Element root = document.getRootElement();
				@SuppressWarnings("unchecked")
				List<Element> fontFamilyList = root.elements(NODE_fontFamily);
				for (Element fontFamily : fontFamilyList) {
					String familyName = fontFamily.attributeValue(ATTRIBUTE_name);
					@SuppressWarnings("unchecked")
					List<Element> fontList = fontFamily.elements();
					for (Element font : fontList) {
						// System.out.println("nodeName:" + font.getName() +
						// "   value:" + font.getText());
						if (NODE_normal.equals(font.getName()) || NODE_bold.equals(font.getName())
								|| NODE_italic.equals(font.getName()) || NODE_boldItalic.equals(font.getName())) {
							FontFactory.register(font.getText());
							FontFactory.registerFamily(familyName, familyName, font.getText());
						}
					}
				}
			} catch (DocumentException e) {
				e.printStackTrace();
			}
		}
		// System.out.println("getRegisteredFonts");
		// Set<String> listx = FontFactory.getRegisteredFonts();
		// for (String str : listx) {
		// System.out.println(str);
		// }
		// System.out.println("getRegisteredFamilies");
		// listx = FontFactory.getRegisteredFamilies();
		// for (String str : listx) {
		// System.out.println(str);
		// }
	}
}
